package com.micro.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
import oauth.signpost.exception.OAuthCommunicationException;
import oauth.signpost.exception.OAuthExpectationFailedException;
import oauth.signpost.exception.OAuthMessageSignerException;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import com.micro.constant.IGeneral;

public class HttpCommunicator {
	public static final String CONSUMER_KEY_SINA = "1906085257";

	public static final String CONSUMER_SECRET_SINA = "5dfb9e4a4ce253061c3f4b8a8628e382";

	@SuppressWarnings("finally")
	protected static CommunicatorResponse httpGetOauth(String service,
			String url, String accessToken, String tokenSecret) {

		synchronized ("http get oauth") {

			// Prepare Result Data
			CommunicatorResponse chResult = new CommunicatorResponse();
			int statusCode = 0;
			String msg = null;

			try {
				CommonsHttpOAuthConsumer consumer = null;
				if (service.equals(IGeneral.SERVICE_NAME_SINA)) {
					// Prepare OAuth Key
					consumer = new CommonsHttpOAuthConsumer(CONSUMER_KEY_SINA,
							CONSUMER_SECRET_SINA);
					consumer.setTokenWithSecret(accessToken, tokenSecret);
				}

				HttpGet httpGet = new HttpGet(url);

				// Prepare HttpClient
				HttpClient httpClient = new DefaultHttpClient();
				HttpParams params = httpClient.getParams();
				HttpConnectionParams.setConnectionTimeout(params, 5000);
				HttpConnectionParams.setSoTimeout(params, 10000);

				// Sign Request With Token
				consumer.sign(httpGet);

				// Get Response
				HttpResponse response = httpClient.execute(httpGet);
				statusCode = response.getStatusLine().getStatusCode();
				InputStream in = response.getEntity().getContent();
				msg = InputStreamToString(in);
				
			} catch (OAuthMessageSignerException e) {
				e.printStackTrace();
			} catch (OAuthExpectationFailedException e) {
				e.printStackTrace();
			} catch (OAuthCommunicationException e) {
				e.printStackTrace();
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				// Set result
				chResult.setMessage(msg);
				chResult.setResponseCode(String.valueOf(statusCode));	
				return chResult;
			}

		}
	}

	// -----------------------------------------------------------------------------------
	/**
	 * Convert InputStream to String
	 * 
	 * @param is
	 *            a instance of InputStream
	 * @return String
	 */
	// -----------------------------------------------------------------------------------
	@SuppressWarnings("finally")
	protected static String InputStreamToString(InputStream is) {

		String value = null;
		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					is, "UTF-8"));
			StringBuffer buf = new StringBuffer();
			String str;

			while ((str = reader.readLine()) != null) {
				buf.append(str);
			}

			value = buf.toString();

		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
			return value;
		}

	}

}
